/**
 * jims
 */
package com.jims.master.modules.sys.service;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.jims.master.common.config.Global;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.TreeService;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.utils.SynchroDataUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.sys.dao.OrgDeptDao;
import com.jims.master.modules.sys.entity.OrgDept;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 机构科室Service
 * @author zhangyao
 * @version 2017-02-17
 */
@Service
@Transactional(readOnly = true)
public class OrgDeptService extends TreeService<OrgDeptDao, OrgDept> {

    @Autowired
    private OrgDeptDao orgDeptDao;

    public OrgDept get(String id) {
		return super.get(id);
	}

    public List<OrgDept> findByParentIdsLike(OrgDept orgDept){
        orgDept.updateOrgId();
        if(orgDept != null){
            orgDept.setParentIds(orgDept.getParentIds()+"%");
            return dao.findByParentIdsLike(orgDept);
        }
        return  new ArrayList<OrgDept>();
    }
    public Page<OrgDept> findPageParentIdsLike(Page<OrgDept> page, OrgDept orgDept) {
        orgDept.updateOrgId();
        orgDept.setPage(page);
        page.setList(dao.findByParentIdsLike(orgDept));
        return page;
    }

	@Transactional(readOnly = false)
	public int save(OrgDept orgDept) {
		return super.save(orgDept);
	}
	
	@Transactional(readOnly = false)
	public int delete(OrgDept orgDept) {
		return super.delete(orgDept);
	}
    /**
     * 根据科室分组名获取ID
     * @param orgDept
     * @return
     * @author DT
     */
    public OrgDept findId(OrgDept orgDept){
        return orgDeptDao.findId(orgDept);
    }

    /**
     * 获取user权限科室
     * @return
     */
    public List<OrgDept> roleDept(String userId){
        return orgDeptDao.roleDept(userId);
    }

    /**
     * 获取所有下级科室
     * @return
     * @author fengyg
     */
    public List<OrgDept> getLowLevelDeptList(){
        return orgDeptDao.getLowLevelDeptList(UserUtils.getUser().getOrgId());
    }

    /**
     * 同步人力资源处科室（webService接口和AMQ通用的方法）
     *
     * @param type      类型   add 新增    update 修改   delete 删除
     * @param orgId     机构id
     * @param inputLine AMQ新增、修改或者删除时从人力资源传递的数据
     * @return
     * @author yangruidong
     */
    @Transactional(readOnly = false)
    public String synchroDept(String type, final String orgId, String inputLine) {
        List<Map<String, Object>> result;
        //判断是AMQ新增还是webService接口同步数据
        if (StringUtils.isBlank(inputLine)) {
            String dict = DictUtils.getDictValue("同步部门", "dept_data", "");
            //访问人力资源同步数据的路径
            String url = Global.getConfig("hrm_ip") + dict;
            if (StringUtils.isNotBlank(orgId)) {
                url = url + "?orgId=" + orgId;
            }
            result = convertList(SynchroDataUtils.getJsonByUrl(url));
        } else {
            result = convertList(inputLine);
        }
        if (result != null) {
            List<OrgDept> depts = findList(new OrgDept());
            Map<String, OrgDept> deptMap = Maps.uniqueIndex(depts, new Function<OrgDept, String>() {
                @Override
                public String apply(OrgDept orgDept) {
                    return orgDept.getId();
                }
            });
            for (int i = 0; i < result.size(); i++) {
                Map<String, Object> map = result.get(i);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    OrgDept orgDept = (OrgDept) entry.getValue();
                    if (StringUtils.equalsIgnoreCase("delete", type)) {
                        //AMQ删除
                        delete(orgDept);
                    }
                    //使用webService同步数据以及修改数据
                    if (deptMap.get(orgDept.getId()) == null) {
                        orgDept.setDelFlag("0");
                        dao.insert(orgDept);
                    } else {
                        orgDept.preUpdate();
                        OrgDept updateDept = deptMap.get(orgDept.getId());
                        orgDept.setParent(updateDept.getParent());
                        orgDept.setOrgId(updateDept.getOrgId());
                        dao.update(orgDept);
                    }
                }
            }
            return "success";
        }
        return null;
    }


    /**
     * 转换，将人力资源传递的数据转成list集合
     *
     * @param json 人力资源地址
     * @return
     */
    public List<Map<String, Object>> convertList(String json) {
        Map<String, String[]> replaceMap = new HashMap<>();
        String namespace = OrgDept.class.getName();
        replaceMap.put("id", new String[]{namespace, "id"});
        replaceMap.put("name", new String[]{namespace, "deptName"});
        replaceMap.put("code", new String[]{namespace, "deptCode"});
        replaceMap.put("sort", new String[]{namespace, "sort"});
        replaceMap.put("parentId", new String[]{namespace, "parent.id"});
        replaceMap.put("orgId", new String[]{namespace, "orgId"});
        replaceMap.put("delFlag", new String[]{namespace, "delFlag"});
        replaceMap.put("createBy", new String[]{namespace, "createBy.id"});
        replaceMap.put("updateBy", new String[]{namespace, "updateBy.id"});
        replaceMap.put("updateDate", new String[]{namespace, "updateDate"});
        replaceMap.put("createDate", new String[]{namespace, "createDate"});

        return SynchroDataUtils.getDataByJson(json, replaceMap);
    }


    /**
     * 获取机构科室
     * @param dto
     * @return
     * @author zhangyao
     * @version 2017-7-25
     */
    public List<BaseDto> getDeptList(BaseDto dto){
        return orgDeptDao.getDeptList(dto);
    }


}


